package com.sixth.aspect;

import com.github.pagehelper.util.StringUtil;
import com.sixth.annotation.SearchRecordAdvice;
import com.sixth.bean.MarketSearchHistory;
import com.sixth.bean.MarketUser;
import com.sixth.mapper.MarketSearchHistoryMapper;
import com.sixth.util.MarketInfoUtil;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * @ClassName SearchRecordAspect
 * @Description TODO
 * @Author XiaoWJ
 * @Date 2022/9/12 19:46
 **/
@Aspect
@Component
public class SearchRecordAspect {

    @Autowired
    MarketSearchHistoryMapper marketSearchHistoryMapper;

    // 切入点

    @Pointcut("@annotation(com.sixth.annotation.SearchRecordAdvice)")
    public void searchRecordPointcut(){}


    // aruond通知

    @SneakyThrows
    @Around("searchRecordPointcut()")
    public Object searchRecord(ProceedingJoinPoint joinPoint){

        // 获取用户id, 若用户为游客，则不实现该切面
        MarketUser marketUser = MarketInfoUtil.getMarketUser();

        Object proceed = null;
        if(marketUser == null ){
            proceed = joinPoint.proceed();
            return proceed;
        }

        MarketSearchHistory history = new MarketSearchHistory();
        // 指定用户id
        history.setUserId(marketUser.getId());

        // 指定关键字
        String keyword = null;
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if(arg instanceof String) {
                keyword = ((String) arg);
                break;
            }
        }

        history.setKeyword(keyword);

        // 获取来源

        // 获取委托类方法
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();

        // 获取方法上的注解
        SearchRecordAdvice annotation = method.getAnnotation(SearchRecordAdvice.class);
        String from = annotation.from();

        // 设置来源
        history.setFrom(from);

        // 插入一条搜索记录
        insertSearchRecord(history);

        // 执行委托类方法，并返回
        proceed = joinPoint.proceed();

        return proceed;

    }

    private void insertSearchRecord(MarketSearchHistory history) {

        // 如果keyword为空，则不插入
        if(StringUtil.isEmpty(history.getKeyword())) {
            return ;
        }
        Date date = new Date();
        history.setAddTime(date);
        history.setUpdateTime(date);
        history.setDeleted(false);

        marketSearchHistoryMapper.insertSelective(history);

    }

}
